package com.gimi.cloud.bbp.manage.controller;

import com.alibaba.fastjson.JSONObject;
import com.gimi.cloud.bbp.common.constant.RedisKeyConstant;
import com.gimi.cloud.bbp.common.enums.ResponseCodeEnum;
import com.gimi.cloud.bbp.common.utils.reqhead.Response;
import com.gimi.cloud.bbp.commonService.redis.RedisService;
import com.gimi.cloud.bbp.dto.sys.SysMasterDTO;
import com.gimi.cloud.bbp.manage.service.sys.SysMasterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 首页访问
 *
 * @author wbj
 * @version 1.0
 * @Description
 * @create 2017-12-22
 **/
@RestController
@RequestMapping("/index")
public class IndexController {
    private static final Logger logger = LoggerFactory.getLogger(IndexController.class);
    private RedisService redisService;
    private SysMasterService sysMasterService;

    @Autowired
    public IndexController(RedisService redisService, SysMasterService sysMasterService) {
        this.redisService = redisService;
        this.sysMasterService = sysMasterService;
    }

    /**
     * 初始化首页，获取菜单及权限信息
     * @param request
     * @param response
     * @param  sysMasterDTO
     * @throws Exception
     */
    @PostMapping("/permission")
    public Response menus(HttpServletRequest request, HttpServletResponse response, @RequestBody SysMasterDTO sysMasterDTO) throws Exception{
        Integer masterId = sysMasterDTO.getUid();
        JSONObject masterPermission = redisService.getJsonObjectByKey(RedisKeyConstant.MANAGE_LOGIN_MASTER_PERMISSION_PREFIX+masterId);
        if(null == masterPermission){
            Response resp = new Response();
            resp.setResponseCode(ResponseCodeEnum.SUCCESSED,"获取成功");
            resp.setRes_data(masterPermission);
            return resp;
        }
        //redis未获取到用户权限信息，从数据库获取
        Map<String,Object> permission = sysMasterService.getMasterPermissions(sysMasterDTO,masterId);
        //重新添加值redis缓存
        redisService.setObject(RedisKeyConstant.MANAGE_LOGIN_MASTER_PERMISSION_PREFIX+masterId,permission);
        Response resp = new Response();
        resp.setResponseCode(ResponseCodeEnum.SUCCESSED,"获取成功");
        resp.setRes_data(permission);
        return resp;
    }
}
